#include "App_Mqtt.h"

// 定义MQTT客户端
static MQTTClient client;
// 定义MQTT连接选项
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
// 定义MQTT消息
static MQTTClient_message pubmsg = MQTTClient_message_initializer;
// 定义MQTT回调函数
static void (*recv_callback)(char *json) = NULL;

// 发送消息完成的回调函数
static void delivered(void *context, MQTTClient_deliveryToken dt)
{
    log_debug("消息发送成功");
}

// 接收到远程消息的回调函数
static int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    log_debug("消息到达");
    log_debug("topic: %s", topicName);
    log_debug("message: %.*s", message->payloadlen, (char *)message->payload);
    if (recv_callback != NULL)
    {
        // 调用回调函数处理消息
        recv_callback((char *)message->payload);
    }
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return 1;
}

// 连接断开回调函数
void connlost(void *context, char *cause)
{
    log_debug("\n连接断开\n");
    log_debug("原因: %s\n", cause);
}

int App_Mqtt_Init(void)
{
    // 1. 创建MQTT客户端
    if (MQTTClient_create(&client, ADDRESS, CLIENTID,
                          MQTTCLIENT_PERSISTENCE_NONE, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_debug("MQTT客户端创建失败\n");
        return -1;
    }
    // 2. 设置回调函数
    if (MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered) != MQTTCLIENT_SUCCESS)
    {
        log_debug("MQTT回调函数设置失败\n");
        return -1;
    }
    // 3. 连接服务器
    if (MQTTClient_connect(client, &conn_opts) != MQTTCLIENT_SUCCESS)
    {
        log_debug("MQTT连接失败\n");
        return -1;
    }
    // 4. 订阅主题
    if (MQTTClient_subscribe(client, TOPIC_RTG, QOS) != MQTTCLIENT_SUCCESS)
    {
        log_debug("MQTT订阅主题失败\n");
        return -1;
    }

    return 0;
}

void App_Mqtt_Deinit(void)
{
    // 1. 断开连接
    MQTTClient_disconnect(client, TIMEOUT);
    // 2. 取消订阅
    MQTTClient_unsubscribe(client, TOPIC_RTG);
    // 3. 销毁客户端
    MQTTClient_destroy(&client);
    // 4. 释放内存
    // free(client);
}

int App_Mqtt_SendJson(char *json)
{
    // 1. 发布消息

    pubmsg.payload = json;
    pubmsg.payloadlen = strlen(json);
    pubmsg.qos = QOS;
    if (MQTTClient_publishMessage(client, TOPIC_GTR, &pubmsg, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_debug("MQTT发布消息失败\n");
        return -1;
    }
    return 0;
}

void App_Mqtt_RegisterCallback(void (*callback)(char *json))
{
    recv_callback = callback;
}
